package se.thoka.twt.client.application;

import java.util.ArrayList;
import java.util.List;

import se.thoka.twt.shared.exceptions.UserLoggedInRequiredException;

public abstract class HistoryComponent {
	
	protected enum Activation {
		ALWAYS {
			@Override
			boolean activate(boolean userLoggedIn) {
				return true;
			}
		},
		USER_SET {
			@Override
			boolean activate(boolean userLoggedIn) {
				return userLoggedIn;
			}
		},
		NO_USER {
			@Override
			boolean activate(boolean userLoggedIn) {
				return !userLoggedIn;
			}
		};
		
		abstract boolean activate(boolean userLoggedIn);
	}

	private final String defaultToken;
	private final List<String> tokens;
	private Activation activation;
	private boolean initiated;
	private boolean active;
	
	public HistoryComponent(Activation activation, String defaultToken, String... historyTokens) {
		if (defaultToken == null) {
			throw new NullPointerException("Default history token must not be null");
		}
		
		this.defaultToken = defaultToken;
		this.tokens = new ArrayList<String>();
		this.tokens.add(defaultToken);
		for (String historyToken : historyTokens) {
			this.tokens.add(historyToken);
		}
		
		this.activation = activation != null ? activation : Activation.ALWAYS;
	}
	
	protected boolean activate(String token, boolean userSet) {
//		GWTLogger.log(getClass().getName() + "#activate(" + token + ", " + userSet + ") -> " + activation.activate(userSet) + " && " + tokens.contains(token));
		return activation.activate(userSet) && tokens.contains(token);
	}
	
	protected Activation getActivation() {
		return activation;
	}
	
	protected boolean isActive() {
		return active;
	}
	
	protected void onInit() throws UserLoggedInRequiredException {}
	
	protected abstract void onShow() throws UserLoggedInRequiredException;
	
	protected abstract void onHide();
	
	protected void onRefresh() {}
	
	protected void setActivation(Activation activation) {
		this.activation = activation;
	}
	
	String getDefaultToken() {
		return defaultToken;
	}
	
	void hide() {
		if (initiated && active) {
			onHide();
		}
		active = false;
	}
	
	void show() throws UserLoggedInRequiredException {
		if (!initiated) {
			onInit();
			initiated = true;
		}
		
		if (!active) {
			onShow();
		} else {
			onRefresh();
		}

		active = true;
	}
}
